<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/23
 * Time: 9:46 AM
 */
namespace app\backend\modules\content\controllers;

use app\backend\controllers\BaseController;
use app\backend\modules\content\services\CategoryService;
use app\common\models\Article;
use app\common\models\Category;
use app\common\models\Page;
use Illuminate\Support\Facades\DB;
use app\backend\modules\sys\services\ThemeService;
use app\common\models\ThemeFile;

class CategoryController extends BaseController
{
    public function index(){
        return view("backend.content.category.index");
    }
    public function getList(){
        $search = request()->search;
        $list = (new CategoryService())->getList($search);
        return $this->successJson('',$list);
    }
    public function detail(){
        return view("backend.content.category.detail");
    }
    public function getDetail(){
        $res = [];
        $themeService = new ThemeService();
        $themeFiles = $themeService->getDefaultTypeFiles();
        $res['pc_list_tpl_list'] = $themeFiles['pc'][ThemeFile::TYPE_ARTICLE_LIST];
        $res['pc_detail_tpl_list'] = $themeFiles['pc'][ThemeFile::TYPE_ARTICLE_DETAIL];
        $res['h5_list_tpl_list'] = $themeFiles['h5'][ThemeFile::TYPE_ARTICLE_LIST];
        $res['h5_detail_tpl_list'] = $themeFiles['h5'][ThemeFile::TYPE_ARTICLE_DETAIL];
        $res['info'] = [];
        $id = intval(request()->id);
        if($id){
            $model = Category::site()->select()
                ->where('id',$id)
                ->first();
            if (empty($model)) {
                return $this->errorJson('未找到数据');
            }
            $model->thumb = fmt_media_url($model->thumb);
            $res['info'] = $model;
        }
        return $this->successJson('',$res);
    }
    public function create(){
        $data = request()->params;
        $data['site_id'] = \YunCms::siteId();
        $data['pid'] = intval($data['pid']);
        $data['display_order'] = intval($data['display_order']);
        $model = new Category();
        $model->fill($data);
        $validator = $model->validator();
        if ($validator->fails()) {
            return $this->errorJson($validator->messages());
        } else {
            $parentPath = '0';
            if ($data['pid']) {
                $parentModel = Category::find($data['pid']);
                if($parentModel['path']){
                    $parentPath = $parentModel['path'];
                }
            }
            DB::transaction(function() use ($model,$parentPath){
                $model->save();
                $model->path = $parentPath.'-'.$model->id;
                $model->save();
            });
            return $this->successJson();
        }
    }
    public function update(){
        $data = request()->params;
        $id = $data['id'];
        $data['pid'] = intval($data['pid']);
        $data['display_order'] = intval($data['display_order']);
        $model = Category::find($id);
        if (empty($model)) {
            $this->errorJson('未找到数据');
        }
        $model->fill($data);
        $validator = $model->validator();
        if ($validator->fails()) {
            return $this->errorJson($validator->messages());
        } else {
            $oldPath = $model['path'];
            $path = '0-'.$id;
            if ($data['pid']) {
                $parentModel = Category::find($data['pid']);
                if($parentModel['path']){
                    $path = $parentModel['path'].'-'.$id;
                }
            }
            $model->path = $path;
            $model->save();
            //修改子栏目path信息
            //如父栏目path=0-2-5，子栏目path=0-2-5-9
            $children = Category::site()->select(['id','path'])
                ->where('path','like',$model['path'].'-%')
                ->get();
            foreach ($children as $child){
                //循环修改子栏目，一般不会太多
                $childPath = str_replace($oldPath . '-', $path . '-', $child['path']);
                Category::where('id', $child['id'])->update(['path' => $childPath]);
            }
        }
        return $this->successJson();
    }
    public function delete(){
        $id = request()->id;
        $model = Category::find($id);
        if(!$model){
            return $this->errorJson('未找到数据');
        }
        $childCount = Category::site()
            ->where('pid',$id)
            ->count();
        if($childCount>0){
            return $this->errorJson('此分类有子类无法删除');
        }
        $usedCount = 0;
        switch ($model['type']){
            case Category::TYPE_ARTICLE:
                $usedCount = Article::site()
                    ->where('cid',$id)
                    ->count();
                break;
            case Category::TYPE_PAGE:
                $usedCount = Page::site()
                    ->where('cid',$id)
                    ->count();
                break;
            default:
                \Log::debug('$model type error ',$model);
                break;
        }
        if($usedCount>0){
            return $this->errorJson('此分类有关联内容无法删除');
        }
        $model->delete();
        return $this->successJson();
    }
    public function changeStatus()
    {
        $id = request()->id;
        $model = Category::site()->select()
            ->where('id',$id)
            ->first();
        if (empty($model)) {
            $this->errorJson('未找到数据');
        }
        $status=Category::STATUS_NORMAL;
        if($model->status==Category::STATUS_NORMAL){
            $status= Category::STATUS_BAN;
        }
        $model->status = $status;
        $model->save();
        return $this->successJson();
    }
    /**
     * 检索分类
     */
    public function query(){
        $kwd = trim(request()->kwd);
        $exceptId = intval(request()->except_id);
        $type = intval(request()->type);
        $list = Category::site()->select(['id','name'])
            ->where('status',Category::STATUS_NORMAL);
        if($type!=Category::TYPE_ALL){
            $list = $list->where('type',$type);
        }
        if($kwd){
            $list = $list->where('name','like','%'.$kwd.'%');
        }
        if($exceptId){
            $list = $list->where('id','<>',$exceptId);
        }
        $list = $list
            ->orderBy('display_order', 'desc')
            ->orderBy('id', 'desc')
            ->take(1000)
            ->get();
        return $this->successJson('',$list);
    }
}